package young.frame;



import young.Util.DBUtil;
import young.Util.Util2;
import young.pojo.UserDO;
import young.service.UserService;
import young.service.impl.UserServiceImpl;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 登陆功能
 */

public class Longin extends JPanel implements ActionListener {
    private Icon longin = Util2.Util.getImageIcon("/img/denglu.jpg");
    private Atm frame;  //ATM frame属性
    private JButton loginBtn; //登陆按钮

    private JTextField userid;
    private JTextField password;
    private int errorCont = 3; //失败次数
    private int count;

    UserService service=new UserServiceImpl();


    public Longin(Atm frame) {

        this.frame = frame;

        this.setLayout(null); //空布局
        this.setOpaque(false); //背景透明
        loginBtn = new JButton(longin); //登陆按钮
        loginBtn.setBounds(320, 500, 120, 50);
        this.add(loginBtn);
        loginBtn.addActionListener(this);

        //账号文本
        userid = new JTextField();
        userid.setBounds(320, 220, 100, 30);
        this.add(userid);
        //密码文本
        password = new JPasswordField();
        password.setBounds(320, 270, 100, 30);
        this.add(password);

        JLabel label = new JLabel("用户名");
        label.setBounds(280, 220, 80, 30);
        this.add(label);

        JLabel label1 = new JLabel("密码");
        label1.setBounds(280, 270, 80, 30);
        this.add(label1);


    }


    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == loginBtn) {
            String id = userid.getText();
            String pwd = password.getText();

            UserDO userDO =service.getByUsernameAndPwd(id,pwd);
            if (userDO !=null){  //判断是否有该账户
                frame.setLoginUser(userDO);  //导入该账户信息
                JOptionPane.showMessageDialog(this, "登录成功");
                frame.switchPanel("菜单");

//            ArrayList<User> users = frame.getUsers();

//            for (int i = 0; i < users.size(); i++) {  //遍历用户对象
//                if (users.get(i).getId().equals(a) && users.get(i).getPassword().equals(b)) { //匹配账户密码
//                    JOptionPane.showMessageDialog(this, "登录成功");
//                    frame.setLoginUser(users.get(i));  // 获取登陆当前对象的信息
                    errorCont = 3;  //登陆成功后，登陆数据还原

                    return;
                }

            errorCont--; //登陆次数自减
            if (errorCont == 0) {
                JOptionPane.showMessageDialog(this, "错误次数过多，24小时后尝试");

                System.exit(0);
            }
            JOptionPane.showMessageDialog(this, "登录失败,还有：" + errorCont + "次机会");
        }

    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}
